package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.shaded.com.google.errorprone.annotations.DoNotCall;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smile.api.OperateLogApi;
import com.smile.api.OssApi;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.time.TimeUtils;
import com.smile.mapper.AirportDroneMapper;
import com.smile.mapper.AirportMapper;
import com.smile.mapper.DeviceModelMapper;
import com.smile.mapper.DroneMapper;
import com.smile.model.domain.FeisuanAirport;
import com.smile.model.domain.FeisuanAirportDrone;
import com.smile.model.domain.FeisuanDeviceModel;
import com.smile.model.domain.FeisuanDrone;
import com.smile.model.dto.request.*;
import com.smile.model.response.response.GetDroneByIdResponseDTO;
import com.smile.model.response.response.GetDroneListResponseDTO;
import com.smile.model.response.response.GetNoBindDroneResponseDTO;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.DroneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DroneServiceImpl implements DroneService {

    @Autowired
    private DroneMapper droneMapper;

    @Autowired
    private OssApi ossApi;

    @Autowired
    private OperateLogApi operateLogApi;

    @Autowired
    private AirportDroneMapper airportDroneMapper;

    @Autowired
    private AirportMapper airportMapper;

    @Autowired
    private DeviceModelMapper deviceModelMapper;

    @Override
    public Boolean addDrone(AddDroneRequestDTO addDroneRequestDTO) throws IOException {
        Long startTime = System.nanoTime();

        FeisuanDrone feisuanDrone = new FeisuanDrone();
        BeanUtil.copyProperties(addDroneRequestDTO, feisuanDrone);
        feisuanDrone.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
//        String fileName = IdWorker.getIdStr() + ".jpg";
//        R<PutFileResponse> putFileResponseR = ossApi.putFile("photo/drone", fileName, addDroneRequestDTO.getDroneImage());
//        if (ObjectUtil.isNotNull(putFileResponseR) || ObjectUtil.isNotNull(putFileResponseR.getData())) {
//            feisuanDrone.setDroneImageUrl(putFileResponseR.getData().getUrl());
//        }
        feisuanDrone.setStatus(1);
        feisuanDrone.setDeleteStatus(Boolean.FALSE);
        feisuanDrone.setCreateTime(LocalDateTime.now());
        feisuanDrone.setModifyTime(LocalDateTime.now());
        feisuanDrone.setTotalTaskTime(0L);
        feisuanDrone.setTotalTaskDistance(0L);
        feisuanDrone.setTaskCount(0L);

        droneMapper.insert(feisuanDrone);

        Long endTime = System.nanoTime();

        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("设备模块");
        addOperateLogRequest.setOperateName("新增无人机设备");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setOperateType(1);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);

        return Boolean.TRUE;
    }


    @Override
    public Boolean checkDrone(AddDroneRequestDTO addDroneRequestDTO,String gateway) throws IOException {
        Long startTime = System.nanoTime();
//        System.out.println(addDroneRequestDTO);
//        return true;
        FeisuanDrone feisuanDrone = new FeisuanDrone();
        QueryWrapper<FeisuanDrone> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("drone_sn", addDroneRequestDTO.getDroneSn());
        FeisuanDrone feisuanDrone1 = droneMapper.selectOne(queryWrapper);
        if(ObjectUtil.isNull(feisuanDrone1)) {

            QueryWrapper<FeisuanAirport> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("gateway_sn", gateway);
            queryWrapper1.last("limit 1");
            FeisuanAirport feisuanAirport = airportMapper.selectOne(queryWrapper1);
            if(ObjectUtil.isNotNull(feisuanAirport)) {
                //
                QueryWrapper<FeisuanDrone> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.eq("drone_sn", addDroneRequestDTO.getDroneSn());
                FeisuanDrone feisuanDrone2 = droneMapper.selectOne(queryWrapper3);
                if(ObjectUtil.isNull(feisuanDrone2)) {
                    QueryWrapper<FeisuanDeviceModel> queryWrapper4 = new QueryWrapper<>();
                    queryWrapper4.eq("device_model_key", addDroneRequestDTO.getDeviceModelKey());
                    queryWrapper4.last("limit 1");
                    FeisuanDeviceModel deviceModel = deviceModelMapper.selectOne(queryWrapper4);
                    if(ObjectUtil.isNotNull(deviceModel)) {
                        feisuanDrone.setDroneName(deviceModel.getModelName());
                        feisuanDrone.setDroneModel(deviceModel.getModelName());
                    }
                    feisuanDrone.setDroneSn(addDroneRequestDTO.getDroneSn());
                    feisuanDrone.setStatus(addDroneRequestDTO.getStatus());
                    feisuanDrone.setDeleteStatus(Boolean.FALSE);
                    feisuanDrone.setCreateTime(LocalDateTime.now());
                    feisuanDrone.setModifyTime(LocalDateTime.now());
                    feisuanDrone.setTotalTaskTime(0L);
                    feisuanDrone.setTotalTaskDistance(0L);
                    feisuanDrone.setTaskCount(0L);
                    feisuanDrone.setOrganizationId(feisuanAirport.getOrganizationId());
                    feisuanDrone.setDeviceModelKey(addDroneRequestDTO.getDeviceModelKey());
                    Integer droneId = droneMapper.insert(feisuanDrone);
                    QueryWrapper<FeisuanAirportDrone> queryWrapper2 = new QueryWrapper<>();
                    queryWrapper2.eq("drone_id", droneId);
                    queryWrapper2.eq("airport_id", feisuanAirport.getId());
                    queryWrapper2.last("limit 1");
                    FeisuanAirportDrone feisuanAirportDrone = airportDroneMapper.selectOne(queryWrapper2);
                    if(ObjectUtil.isNull(feisuanAirportDrone)) {
                        FeisuanAirportDrone newDrone = new FeisuanAirportDrone();
                        newDrone.setDroneId(feisuanDrone.getId());
                        newDrone.setAirportId(feisuanAirport.getId());
                        airportDroneMapper.insert(newDrone);
                    }
                }

            }
        }else{
            feisuanDrone1.setStatus(addDroneRequestDTO.getStatus());
            feisuanDrone1.setModifyTime(LocalDateTime.now());
            droneMapper.updateById(feisuanDrone1);
        }


        return Boolean.TRUE;
    }

    @Override
    public Boolean editDrone(EditDroneRequestDTO editDroneRequestDTO) throws IOException {
        Long startTime = System.nanoTime();

        UpdateWrapper<FeisuanDrone> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("drone_sn", editDroneRequestDTO.getDroneSn());
        if (ObjectUtil.isNotNull(editDroneRequestDTO)) {

//            if (ObjectUtil.isNotNull(editDroneRequestDTO.getDroneImageUrl())) {
//                FeisuanDrone feisuanDrone = droneMapper.selectById(editDroneRequestDTO.getId());
//                if (ObjectUtil.isNotNull(feisuanDrone)) {
////                    DeleteFileRequest request = new DeleteFileRequest();
////                    request.setPath("photo/drone");
////                    request.setFileName(feisuanDrone.getDroneImageUrl());
////                    ossApi.deleteFile(request);
////                    String url = IdWorker.getIdStr() + ".jpg";
////                    PutFileRequest putFileRequest = new PutFileRequest();
////                    putFileRequest.setFileName(url);
////                    putFileRequest.setPutFileRequest(editDroneRequestDTO.getDroneImageUrl());
////                    putFileRequest.setPath("photo/drone");
//
//                    ossApi.putFile("photo/drone", url, editDroneRequestDTO.getDroneImageUrl());
//                    updateWrapper.set("drone_image_url", url);
//                }
//            }


            updateWrapper.set(StrUtil.isNotBlank(editDroneRequestDTO.getImageUrl()), "image_url", editDroneRequestDTO.getImageUrl());

            updateWrapper.set("modify_time", LocalDateTime.now());
            if (StrUtil.isNotBlank(editDroneRequestDTO.getDroneName())) {
                updateWrapper.set("drone_name", editDroneRequestDTO.getDroneName());
            }
            if (StrUtil.isNotBlank(editDroneRequestDTO.getDroneNo()))
                updateWrapper.set("drone_no", editDroneRequestDTO.getDroneNo());
            if (StrUtil.isNotBlank(editDroneRequestDTO.getDroneModel())) {
                updateWrapper.set("drone_model", editDroneRequestDTO.getDroneModel());
            }
            if (StrUtil.isNotBlank(editDroneRequestDTO.getDroneBrand())) {
                updateWrapper.set("drone_brand", editDroneRequestDTO.getDroneBrand());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getLongitude())) {
                updateWrapper.set("longitude", editDroneRequestDTO.getLongitude());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getLatitude())){
                updateWrapper.set("latitude", editDroneRequestDTO.getLatitude());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getAttitudeHead())){
                updateWrapper.set("attitude_head", editDroneRequestDTO.getAttitudeHead());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getFlightId())){
                updateWrapper.set("flight_id", editDroneRequestDTO.getFlightId());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getFlightStatus())){
                updateWrapper.set("flight_status", editDroneRequestDTO.getFlightStatus());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getFirmwareUpgradeStatus())){
                updateWrapper.set("firmware_upgrade_status", editDroneRequestDTO.getFirmwareUpgradeStatus());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getFirmwareVersion())){
                updateWrapper.set("firmware_version", editDroneRequestDTO.getFirmwareVersion());
            }


            if (ObjectUtil.isNotNull(editDroneRequestDTO.getLastMaintainTime())) {
                updateWrapper.set("last_maintain_time", editDroneRequestDTO.getLastMaintainTime());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getLastMaintainFlightSorties())) {
                updateWrapper.set("last_maintain_flight_sorties", editDroneRequestDTO.getLastMaintainFlightSorties());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getMaintainState())) {
                updateWrapper.set("maintain_state", editDroneRequestDTO.getMaintainState());
            }
            if (ObjectUtil.isNotNull(editDroneRequestDTO.getLastMaintainType())) {
                updateWrapper.set("last_maintain_type", editDroneRequestDTO.getLastMaintainType());
            }
            if (ObjectUtil.isNotNull(editDroneRequestDTO.getLastMaintainFlightTime())) {
                updateWrapper.set("last_maintain_flight_time", editDroneRequestDTO.getLastMaintainFlightTime());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getDroneBatteryMaintenanceState())) {
                updateWrapper.set("drone_battery_maintenance_state", editDroneRequestDTO.getDroneBatteryMaintenanceState());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getDroneBatteryMaintenanceTimeLeft())) {
                updateWrapper.set("drone_battery_maintenance_time_left", editDroneRequestDTO.getDroneBatteryMaintenanceTimeLeft());
            }

            if (ObjectUtil.isNotNull(editDroneRequestDTO.getMediaUploadTime())) {
                updateWrapper.set("media_upload_time", editDroneRequestDTO.getMediaUploadTime());
            }
            updateWrapper.set("modify_time", LocalDateTime.now());
            droneMapper.update(new FeisuanDrone(), updateWrapper);
        }

        Long endTime = System.nanoTime();

//        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
//        addOperateLogRequest.setOperateModule("设备模块");
//        addOperateLogRequest.setOperateName("编辑无人机设备");
//        addOperateLogRequest.setOperateResult(Boolean.TRUE);
//        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
//        addOperateLogRequest.setOperateType(1);
//        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
//        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
//        addOperateLogRequest.setTimes(endTime - startTime);
//        operateLogApi.addOperateLogRequest(addOperateLogRequest);

        return Boolean.TRUE;
    }

    @Override
    public Page<GetDroneListResponseDTO> getDroneList(GetDroneListRequestDTO getDroneListRequestDTO) {
        QueryWrapper<FeisuanDrone> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_status", Boolean.FALSE);
        if (ObjectUtil.isNotNull(getDroneListRequestDTO)) {
            if (StrUtil.isNotBlank(getDroneListRequestDTO.getDroneName())) {
                queryWrapper.eq("drone_name", getDroneListRequestDTO.getDroneName());
            }
            if (ObjectUtil.isNotNull(getDroneListRequestDTO.getStatus())) {
                queryWrapper.eq("status", getDroneListRequestDTO.getStatus());
            }
        }
        Page<FeisuanDrone> feisuanDronePage = droneMapper.selectPage(new Page<>(getDroneListRequestDTO.getCurrentPage(), getDroneListRequestDTO.getPageSize()), queryWrapper);

        Page<GetDroneListResponseDTO> getDroneListResponseDTOPage = MyBatisPlusPageConverter.convertPage(feisuanDronePage, GetDroneListResponseDTO.class);
        getDroneListResponseDTOPage.setRecords(
                feisuanDronePage.getRecords().stream().map(i -> {
                    GetDroneListResponseDTO getDroneListResponseDTO = BeanUtil.copyProperties(i, GetDroneListResponseDTO.class);
                    switch (i.getStatus()) {
                        case 1:
                            getDroneListResponseDTO.setStatus("作业中");
                            break;
                        case 2:
                            getDroneListResponseDTO.setStatus("待命");
                            break;
                        case 3:
                            getDroneListResponseDTO.setStatus("离线");
                            break;
                    }
                    getDroneListResponseDTO.setAirportName("大疆机场");
                    getDroneListResponseDTO.setFeishouUserName("宁海博");
                    return getDroneListResponseDTO;
                }).collect(Collectors.toList())
        );

        return getDroneListResponseDTOPage;
    }

    @Override
    public GetDroneByIdResponseDTO getDroneById(GetDroneByIdRequestDto getDroneByIdRequestDto) {
        QueryWrapper<FeisuanDrone> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("delete_status", Boolean.FALSE);
        queryWrapper.eq("id", getDroneByIdRequestDto.getId());
        FeisuanDrone feisuanDrone = droneMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNull(feisuanDrone)) {
            throw new RuntimeException("该飞机不存在");
        } else {
            GetDroneByIdResponseDTO getDroneByIdResponseDTO = BeanUtil.copyProperties(feisuanDrone, GetDroneByIdResponseDTO.class);
            getDroneByIdResponseDTO.setImageUrl(feisuanDrone.getImageUrl());

            switch (feisuanDrone.getStatus()) {
                case 1:
                    getDroneByIdResponseDTO.setStatus("作业中");
                    break;
                case 2:
                    getDroneByIdResponseDTO.setStatus("待命");
                    break;
                case 3:
                    getDroneByIdResponseDTO.setStatus("离线");
                    break;
            }

            getDroneByIdResponseDTO.setTotalTaskTime(TimeUtils.toChineseTime(feisuanDrone.getTotalTaskTime()));

//            getDroneByIdResponseDTO.setTaskCount(100L);
            getDroneByIdResponseDTO.setTotalTaskTime("39小时21分钟23秒");
//            getDroneByIdResponseDTO.setTotalTaskDistance("7368米");
            return getDroneByIdResponseDTO;
        }
    }

    @Override
    public Boolean deleteDrone(Long id) {
        if (ObjectUtil.isNull(id)) {
            return false;
        }

        Long startTime = System.nanoTime();

        UpdateWrapper<FeisuanDrone> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id).set("delete_status", Boolean.TRUE);
//        droneMapper.update(new FeisuanDrone(), updateWrapper);
        droneMapper.delete(updateWrapper);

        Long endTime = System.nanoTime();


        AddOperateLogRequest addOperateLogRequest = new AddOperateLogRequest();
        addOperateLogRequest.setOperateModule("设备模块");
        addOperateLogRequest.setOperateName("删除无人机设备");
        addOperateLogRequest.setOperateResult(Boolean.TRUE);
        addOperateLogRequest.setUserId(Long.valueOf(StpUtil.getLoginId().toString()));
        addOperateLogRequest.setOperateType(1);
        addOperateLogRequest.setIpAddress(ActionUtils.getIpInfo());
        addOperateLogRequest.setExplorer(ActionUtils.getExplorerInfo());
        addOperateLogRequest.setTimes(endTime - startTime);
        operateLogApi.addOperateLogRequest(addOperateLogRequest);


        return Boolean.TRUE;
    }

    @Override
    public Page<GetNoBindDroneResponseDTO> getNoBindDrone(GetNoBindDroneRequestDTO getNoBindDroneRequestDTO) {
        List<FeisuanAirportDrone> feisuanAirportDrones = airportDroneMapper.selectList(null);


        QueryWrapper<FeisuanDrone> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(getNoBindDroneRequestDTO.getDroneName()), "drone_name", getNoBindDroneRequestDTO.getDroneName());
        if (CollectionUtil.isNotEmpty(feisuanAirportDrones)) {
            queryWrapper.notIn("id", feisuanAirportDrones.stream().map(i -> i.getDroneId()).collect(Collectors.toList()));
        }
        Page<FeisuanDrone> feisuanDronePage = droneMapper.selectPage(new Page<>(getNoBindDroneRequestDTO.getCurrentPage(), getNoBindDroneRequestDTO.getPageSize()), queryWrapper);
        return MyBatisPlusPageConverter.convertPage(feisuanDronePage, GetNoBindDroneResponseDTO.class);
    }


}
